package com.roroldo.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    /**
     * 正常访问，一切OK
     */
    public String paymentInfo_OK(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + "paymentInfo_OK,id: " + id + "\t" + "O(∩_∩)O";
    }

     /**
     * 超时访问，演示服务降级（处理方法必须放在同一个类中）
     */
     @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",
     commandProperties = {
             @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
     })
    public String paymentInfo_TimeOut(Integer id) {
         // 2. 出现异常
         // int i = 1 / 0;
         // 1. 服务超时
         long timeout = 5;
         try {
             TimeUnit.SECONDS.sleep(timeout);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut,id: " + id + "\t" + "O(∩_∩)O，耗费" + timeout +"秒";
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "/(ㄒoㄒ)/调用支付接口超时或异常：\t" + "\t当前线程池名字" + Thread.currentThread().getName();
    }

    /**
     * ====> 服务熔断
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",
            commandProperties = {
            // 参数详细信息在 HystrixCommandProperties 类中
            // 完整意思：在时间窗口期内，请求达到 10次，失败次数达到 60%，就有熔断了
                // 是否开启断路器
                @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
                // 请求次数
                @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                // 时间窗口期
                @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                // 失败率达到多少后跳闸
                @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if(id < 0) {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }
}
